const regionData = require('../../utils/region-data');
const tokenManager = require('../../utils/tokenManager');
const api = require('../../api/index');

Page({
  data: {
    // 表单数据
    formData: {
      // 身份信息字段
      real_name: '',
      gender: '',
      birth_date: '',
      id_card: '',
      nationality: '',
      native_province: '',
      native_city: '',
      native_district: '',
      political_status: '',
      marital_status: '',
      // 教育信息字段
      education_level: '',
      school: '',
      school_level: '',
      major: '',
      major_category: '',
      enrollment_year: '',
      expected_graduation: '',
      is_graduated: false,
      gpa: '',
      gpa_ranking: '',
      academic_achievements: ''
    },
    // 选择器数据
    pickerRanges: {
      gender: ['男', '女', '其他'],
      idtype: ['居民身份证', '护照', '其他'],
      nationality: ['中国', '美国', '英国', '日本', '韩国', '法国', '德国', '俄罗斯', '加拿大', '澳大利亚', '新加坡', '马来西亚', '泰国', '越南', '印度', '其他'],
      politicalstatus: ['群众', '团员', '党员', '其他'],
      maritalstatus: ['未婚', '已婚', '离异', '丧偶'],
      educationlevel: ['专科', '本科', '硕士', '博士'],
      isgraduated: ['未毕业', '已毕业'],
      schoollevel: ['985', '211', '双一流', '普通本科', '高职高专']
    },
    // 省市区数据
    regionData: regionData,
    // 当前选中的省市区索引
    regionIndex: [0, 0, 0],
    // 省市区选择器范围
    regionRange: [],
    // 表单状态
    formStatus: {
      loading: false,
      submitEnabled: true,
      isEdit: false,
      identityId: ''
    },
    loading: false,
    error: null
  },

  onLoad() {
    // 设置默认值，确保新用户有初始值
    this.setDefaultValues();
    
    // 初始化省市区数据
    this.updateRegionRange();
    
    // 加载用户资料
    this.loadUserProfile();
    
    // 输出日志检查默认值是否正确设置
    console.log('页面加载后的表单数据:', this.data.formData);
  },

  // 加载用户资料
  loadUserProfile() {
    if (!tokenManager.isLoggedIn()) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true, error: null });

    const token = tokenManager.getAccessToken();
    api.user.getStudentProfile(token)
      .then(studentProfile => {
        console.log('获取到的学生档案信息:', studentProfile);
        if (studentProfile) {
          this.fillFormData(studentProfile);
        } else {
          console.warn('获取到的学生档案信息为空');
          // 新用户设置默认值
          this.setDefaultValues();
        }
        this.setData({ loading: false });
      })
      .catch(error => {
        console.error('获取学生档案信息失败:', error);
        this.setData({ 
          loading: false,
          error: '获取个人信息失败，请稍后重试'
        });
        // 错误情况下也设置默认值，避免表单空白
        this.setDefaultValues();
        wx.showToast({
          title: '获取个人信息失败',
          icon: 'error'
        });
      });
  },

  // 为新用户设置默认值
  setDefaultValues() {
    const defaultValues = {
      political_status: '群众',
      marital_status: '未婚',
      education_level: '本科',
      school_level: '普通本科',
      is_graduated: '未毕业'
    };
    
    // 只设置为空的字段，避免覆盖已有值
    const formData = this.data.formData;
    for (const key in defaultValues) {
      if (!formData[key]) {
        formData[key] = defaultValues[key];
      }
    }
    
    this.setData({ formData }, () => {
      console.log('新用户表单默认值已设置:', formData);
    });
  },

  // 填充表单数据
  fillFormData(studentProfile) {
    if (!studentProfile) {
      // 对于新用户，设置默认值
      const defaultFormData = {
        political_status: '群众',
        marital_status: '未婚',
        education_level: '本科',
        school_level: '普通本科',
        is_graduated: '未毕业'
      };
      
      this.setData({ 
        formData: { ...this.data.formData, ...defaultFormData }
      }, () => {
        console.log('新用户表单数据已设置默认值:', this.data.formData);
      });
      return;
    }
    
    console.log('开始填充表单数据:', studentProfile);
    
    // 转换婚姻状况
    const maritalStatusMap = {
      'Single': '未婚',
      'Married': '已婚',
      'Divorced': '离异',
      'Widowed': '丧偶'
    };
    
    // 转换学校层次
    const schoolLevelMap = {
      '985': '985',
      '211': '211',
      '双一流': '双一流',
      '普通本科': '普通本科',
      '高职高专': '高职高专'
    };

    // 转换学历层次
    const educationLevelMap = {
      '专科': '专科',
      '本科': '本科',
      '硕士': '硕士',
      '博士': '博士'
    };
    
    // 转换是否已毕业状态
    let isGraduated = '未毕业';
    if (studentProfile.is_graduated !== undefined && studentProfile.is_graduated !== null) {
      // 将各种格式转换为布尔值
      let graduated = false;
      if (typeof studentProfile.is_graduated === 'string') {
        graduated = studentProfile.is_graduated.toLowerCase() === 'true' || 
                    studentProfile.is_graduated === '1';
      } else {
        graduated = Boolean(studentProfile.is_graduated);
      }
      
      isGraduated = graduated ? '已毕业' : '未毕业';
      console.log('毕业状态转换:', studentProfile.is_graduated, '->', isGraduated);
    }

    // 安全地解析籍贯信息
    let nativeProvince = '', nativeCity = '', nativeDistrict = '', nativePlace = '';
    try {
      if (studentProfile.native_place) {
        // 移除多余的空格并按空格分割
        const parts = studentProfile.native_place.trim().split(/\s+/);
        console.log('籍贯解析结果:', parts);
        
        if (parts.length >= 1) {
          nativeProvince = parts[0] || '';
          // 在省份后面加上"省"/"市"（如果没有的话）
          if (!nativeProvince.endsWith('省') && !nativeProvince.endsWith('市') && 
              !nativeProvince.endsWith('自治区') && !nativeProvince.endsWith('特别行政区')) {
            // 检查是否是直辖市
            if (['北京', '上海', '天津', '重庆'].includes(nativeProvince)) {
              nativeProvince += '市';
            } else {
              nativeProvince += '省';
            }
          }
        }
        if (parts.length >= 2) {
          nativeCity = parts[1] || '';
          // 在城市后面加上"市"（如果没有的话）
          if (!nativeCity.endsWith('市') && !nativeCity.endsWith('地区') && 
              !nativeCity.endsWith('自治州') && !nativeCity.endsWith('盟')) {
            nativeCity += '市';
          }
        }
        if (parts.length >= 3) {
          nativeDistrict = parts[2] || '';
          // 在区县后面加上"区"/"县"（如果没有的话）
          if (!nativeDistrict.endsWith('区') && !nativeDistrict.endsWith('县') && 
              !nativeDistrict.endsWith('市') && !nativeDistrict.endsWith('旗')) {
            nativeDistrict += '区';
          }
        }
        
        // 组装完整的籍贯信息
        nativePlace = [nativeProvince, nativeCity, nativeDistrict].filter(Boolean).join('');
      }
    } catch (error) {
      console.warn('解析籍贯信息失败:', error);
    }

    // 安全地解析学术成就
    let academicAchievements = '';
    try {
      if (studentProfile.academic_achievements) {
        if (typeof studentProfile.academic_achievements === 'string') {
          const parsed = JSON.parse(studentProfile.academic_achievements);
          academicAchievements = parsed.content || '';
        } else if (typeof studentProfile.academic_achievements === 'object') {
          academicAchievements = studentProfile.academic_achievements.content || '';
        }
      }
    } catch (error) {
      console.warn('解析学术成就失败:', error);
      academicAchievements = '';
    }

    // 处理日期格式
    let birthDate = '';
    try {
      if (studentProfile.birth_date) {
        const date = new Date(studentProfile.birth_date);
        birthDate = date.toISOString().split('T')[0];
      }
    } catch (error) {
      console.warn('解析出生日期失败:', error);
    }

    let expectedGraduation = '';
    try {
      if (studentProfile.expected_graduation) {
        const date = new Date(studentProfile.expected_graduation);
        expectedGraduation = date.toISOString().split('T')[0];
      }
    } catch (error) {
      console.warn('解析预计毕业时间失败:', error);
    }

    const formData = {
      // 身份信息
      real_name: studentProfile.real_name || '',
      gender: studentProfile.gender === 'M' ? '男' : studentProfile.gender === 'F' ? '女' : '其他',
      birth_date: birthDate,
      id_card: studentProfile.id_card || '',
      nationality: studentProfile.nationality || '',
      native_place: nativePlace,
      native_province: nativeProvince,
      native_city: nativeCity,
      native_district: nativeDistrict,
      political_status: studentProfile.political_status || '',
      marital_status: maritalStatusMap[studentProfile.marital_status] || '未婚',
      // 教育信息
      education_level: educationLevelMap[studentProfile.education_level] || '本科',
      school: studentProfile.school || '',
      school_level: schoolLevelMap[studentProfile.school_level] || '普通本科',
      major: studentProfile.major || '',
      major_category: studentProfile.major_category || '',
      enrollment_year: studentProfile.enrollment_year || '',
      expected_graduation: expectedGraduation,
      is_graduated: isGraduated,
      gpa: studentProfile.gpa ? studentProfile.gpa.toString() : '',
      gpa_ranking: studentProfile.gpa_ranking || '',
      academic_achievements: academicAchievements
    };
    
    console.log('填充后的表单数据:', formData);
    
    // 先更新表单数据
    this.setData({ formData }, () => {
      console.log('表单数据已更新:', this.data.formData);
      // 然后更新省市区选择器的索引
      this.updateRegionIndexByAddress(nativeProvince, nativeCity, nativeDistrict);
    });
  },

  // 根据地址更新省市区选择器的索引
  updateRegionIndexByAddress(province, city, district) {
    const { regionData } = this.data;
    let provinceIndex = 0, cityIndex = 0, districtIndex = 0;

    // 查找省份索引
    const provinces = regionData.provinces;
    provinceIndex = provinces.findIndex(p => {
      const pName = p.name.replace(/省|市|自治区|特别行政区/, '');
      const provinceName = province.replace(/省|市|自治区|特别行政区/, '');
      return pName === provinceName;
    });
    if (provinceIndex === -1) provinceIndex = 0;

    // 查找城市索引
    if (provinceIndex >= 0) {
      const currentProvince = provinces[provinceIndex];
      const cities = regionData.cities[currentProvince.code] || [];
      cityIndex = cities.findIndex(c => {
        const cName = c.name.replace(/市|地区|自治州|盟/, '');
        const cityName = city.replace(/市|地区|自治州|盟/, '');
        return cName === cityName;
      });
      if (cityIndex === -1) cityIndex = 0;

      // 查找区县索引
      if (cityIndex >= 0) {
        const currentCity = cities[cityIndex];
        // 添加null检查，确保currentCity和currentCity.code都存在
        const districts = (currentCity && currentCity.code) ? regionData.districts[currentCity.code] || [] : [];
        districtIndex = districts.findIndex(d => {
          const dName = d.name.replace(/区|县|市|旗/, '');
          const districtName = district.replace(/区|县|市|旗/, '');
          return dName === districtName;
        });
        if (districtIndex === -1) districtIndex = 0;
      }
    }

    console.log('更新省市区索引:', [provinceIndex, cityIndex, districtIndex]);

    // 更新选择器索引
    this.setData({
      regionIndex: [provinceIndex, cityIndex, districtIndex]
    }, () => {
      // 更新选择器范围
      this.updateRegionRange();
    });
  },

  // 提交表单
  handleSubmit() {
    if (!this.validateForm()) {
      return;
    }
    
    this.setData({
      'formStatus.loading': true,
      'formStatus.submitEnabled': false
    });
    
    // 直接获取 token，不使用 Promise 链式调用
    const token = tokenManager.getAccessToken();
    
    if (!token) {
      this.setData({
        'formStatus.loading': false,
        'formStatus.submitEnabled': true
      });
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载提示
    wx.showLoading({
      title: '提交中...',
      mask: true
    });
    
    // 准备提交数据
    const formData = { ...this.data.formData };
    
    // 准备籍贯数据
    if (formData.native_province || formData.native_city || formData.native_district) {
      formData.native_place = [
        formData.native_province, 
        formData.native_city, 
        formData.native_district
      ].filter(Boolean).join(' ');
    }
    
    // 转换是否已毕业字段
    if (formData.is_graduated) {
      // 如果有内部存储的布尔值，优先使用
      if (formData._is_graduated_value !== undefined) {
        formData.is_graduated = formData._is_graduated_value;
      } else {
        // 否则根据文本判断
        formData.is_graduated = formData.is_graduated === '已毕业';
      }
    }
    
    // 移除内部辅助字段
    delete formData._is_graduated_value;
    delete formData.native_province;
    delete formData.native_city;
    delete formData.native_district;
    
    console.log('准备提交的表单数据:', formData);

    // 转换婚姻状况
    const maritalStatusMap = {
      '未婚': 'Single',
      '已婚': 'Married',
      '离异': 'Divorced',
      '丧偶': 'Widowed'
    };
    
    // 转换学校层次
    const schoolLevelMap = {
      '985': '985',
      '211': '211',
      '双一流': '双一流',
      '普通本科': '普通本科',
      '高职高专': '高职高专'
    };

    // 转换学历层次
    const educationLevelMap = {
      '专科': '专科',
      '本科': '本科',
      '硕士': '硕士',
      '博士': '博士'
    };

    const submitData = {
      real_name: formData.real_name,
      gender: formData.gender === '男' ? 'M' : formData.gender === '女' ? 'F' : 'O',
      birth_date: formData.birth_date,
      id_card: formData.id_card,
      nationality: formData.nationality,
      native_place: formData.native_place,
      political_status: formData.political_status,
      marital_status: maritalStatusMap[formData.marital_status] || 'Single',
      education_level: educationLevelMap[formData.education_level] || '本科',
      school: formData.school,
      school_level: schoolLevelMap[formData.school_level] || '普通本科',
      major: formData.major,
      major_category: formData.major_category,
      enrollment_year: formData.enrollment_year,
      expected_graduation: formData.expected_graduation,
      is_graduated: formData.is_graduated ? 1 : 0,
      gpa: formData.gpa ? parseFloat(formData.gpa) : null,
      gpa_ranking: formData.gpa_ranking,
      academic_achievements: formData.academic_achievements ? JSON.stringify({ content: formData.academic_achievements }) : null
    };

    api.user.updateStudentProfile(token, submitData)
      .then(response => {
        wx.hideLoading();
        this.setData({
          'formStatus.loading': false,
          'formStatus.submitEnabled': true
        });
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        });
        setTimeout(() => {
          // 跳转到职业规划页面
          wx.redirectTo({
            url: '/pages/career-plan/career-plan',
            success: () => {
              console.log('跳转到职业规划页面成功');
            },
            fail: (err) => {
              console.error('页面跳转失败:', err);
              wx.showToast({
                title: '页面跳转失败',
                icon: 'error'
              });
            }
          });
        }, 1500);
      })
      .catch(error => {
        wx.hideLoading();
        this.setData({
          'formStatus.loading': false,
          'formStatus.submitEnabled': true
        });
        wx.showToast({
          title: '提交失败',
          icon: 'error'
        });
        console.error('提交失败:', error);
      });
  },

  // 表单输入处理
  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`formData.${field}`]: e.detail.value
    });
  },

  // 选择器变化处理
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    console.log('选择器变更:', field, value);
    
    // 处理日期选择器(生日、毕业时间等)
    if (field === 'birth_date' || field === 'expected_graduation') {
      this.setData({
        [`formData.${field}`]: value
      });
      console.log(`日期字段 ${field} 已更新为:`, value);
      return;
    }
    
    // 处理年份选择器
    if (field === 'enrollment_year') {
      this.setData({
        [`formData.${field}`]: value
      });
      console.log(`年份字段 ${field} 已更新为:`, value);
      return;
    }
    
    // 映射字段名称到对应的pickerRanges键
    let rangeKey = field;
    switch(field) {
      case 'political_status':
        rangeKey = 'politicalstatus';
        break;
      case 'marital_status':
        rangeKey = 'maritalstatus';
        break;
      case 'education_level':
        rangeKey = 'educationlevel';
        break;
      case 'school_level':
        rangeKey = 'schoollevel';
        break;
      case 'is_graduated':
        rangeKey = 'isgraduated';
        break;
    }
    
    // 处理普通选择器
    if (this.data.pickerRanges[rangeKey]) {
      const selectedValue = this.data.pickerRanges[rangeKey][value];
      
      // 使用setData直接更新，确保视图会刷新
      let updateData = {};
      updateData[`formData.${field}`] = selectedValue;
      
      // 特殊处理是否已毕业字段
      if (field === 'is_graduated') {
        updateData['formData._is_graduated_value'] = selectedValue === '已毕业';
      }
      
      this.setData(updateData);
      console.log(`字段 ${field} 已更新为:`, selectedValue);
    } else {
      console.warn(`未找到字段 ${field} 对应的选择器范围`, rangeKey);
    }
  },

  // NFC点击处理
  handleNfcTap() {
    wx.showLoading({
      title: '准备读取身份证...',
      mask: true
    });
    
    // 模拟NFC读取
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '请将身份证靠近手机背面',
        icon: 'none'
      });
      
      // 模拟读取成功
      setTimeout(() => {
        this.setData({
          'formData.real_name': '张三',
          'formData.gender': '男',
          'formData.id_card': '512321199904019238',
          'formData.nationality': '汉族',
          'formData.birth_date': '1999-04-01'
        });
        wx.showToast({
          title: '身份证信息读取成功',
          icon: 'success'
        });
      }, 2000);
    }, 1000);
  },

  // 验证教育信息
  handleVerifyTap() {
    wx.navigateTo({
      url: '/pages/education-form/education-form'
    });
  },

  // 处理switch开关切换事件
  handleSwitchChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`formData.${field}`]: e.detail.value
    });
  },

  // 表单验证
  validateForm() {
    console.log('开始验证表单数据:', this.data.formData);
    
    // 必填字段验证
    const requiredFields = [
      'real_name', 'gender', 'birth_date', 'id_card',
      'nationality', 'native_place', 'political_status', 
      'marital_status', 'education_level', 'school', 
      'major', 'enrollment_year', 'expected_graduation'
    ];
    
    for (const field of requiredFields) {
      const value = this.data.formData[field];
      if (!value || (typeof value === 'string' && value.trim() === '')) {
        console.error(`字段 ${field}(${this.getFieldName(field)}) 为空或无效`, value);
        wx.showToast({
          title: `请填写${this.getFieldName(field)}`,
          icon: 'none',
          duration: 2000
        });
        return false;
      }
    }
    
    // GPA验证 - 如果有填写，确保是有效数字
    if (this.data.formData.gpa) {
      const gpa = parseFloat(this.data.formData.gpa);
      if (isNaN(gpa) || gpa < 0 || gpa > 5) {
        console.error('GPA值无效:', this.data.formData.gpa);
        wx.showToast({
          title: 'GPA应为0-5之间的数字',
          icon: 'none',
          duration: 2000
        });
        return false;
      }
    }
    
    console.log('表单验证通过');
    return true;
  },

  // 获取字段中文名
  getFieldName(field) {
    const fieldNames = {
      'real_name': '姓名',
      'gender': '性别',
      'birth_date': '出生日期',
      'id_card': '身份证号',
      'nationality': '国籍',
      'native_place': '籍贯',
      'political_status': '政治面貌',
      'marital_status': '婚姻状况',
      'education_level': '学历层次',
      'school': '学校名称',
      'school_level': '学校层次',
      'major': '专业名称',
      'major_category': '专业类别',
      'enrollment_year': '入学年份',
      'expected_graduation': '预计毕业时间',
      'is_graduated': '是否毕业',
      'gpa': 'GPA',
      'gpa_ranking': 'GPA排名',
      'academic_achievements': '学术成就'
    };
    return fieldNames[field] || field;
  },

  // 更新省市区选择器的范围
  updateRegionRange() {
    const { regionData, regionIndex } = this.data;
    
    // 获取所有省份
    const provinces = regionData.provinces;
    const provinceNames = provinces.map(p => p.name);
    
    // 获取当前选中省份的城市
    const currentProvince = provinces[regionIndex[0]] || {};
    const cities = regionData.cities[currentProvince.code] || [];
    const cityNames = cities.map(c => c.name);
    
    // 获取当前选中城市的区县
    const currentCity = cities[regionIndex[1]] || {};
    const districts = regionData.districts[currentCity.code] || [];
    const districtNames = districts.map(d => d.name);
    
    console.log('更新省市区范围:', {
      provinces: provinceNames,
      cities: cityNames,
      districts: districtNames
    });
    
    // 更新选择器数据
    this.setData({
      regionRange: [provinceNames, cityNames, districtNames]
    });
  },

  // 处理省市区选择器列变化
  handleRegionColumnChange(e) {
    const { column, value } = e.detail;
    const { regionData, regionIndex } = this.data;
    const newRegionIndex = [...regionIndex];
    newRegionIndex[column] = value;

    // 当省份改变时，重置市和区的索引
    if (column === 0) {
      newRegionIndex[1] = 0;
      newRegionIndex[2] = 0;
    }
    // 当市改变时，重置区的索引
    else if (column === 1) {
      newRegionIndex[2] = 0;
    }

    this.setData({ regionIndex: newRegionIndex }, () => {
      // 更新选择器数据
      this.updateRegionRange();
    });
  },

  // 处理省市区选择器确认
  handleRegionChange(e) {
    const { regionData, regionIndex } = this.data;
    const provinces = regionData.provinces;
    const province = provinces[regionIndex[0]] || {};
    
    const cities = regionData.cities[province.code] || [];
    const city = cities[regionIndex[1]] || {};
    
    const districts = regionData.districts[city.code] || [];
    const district = districts[regionIndex[2]] || {};

    // 组装完整的籍贯信息
    const addressParts = [
      province.name,
      city.name,
      district.name
    ].filter(Boolean); // 过滤掉空值

    const fullAddress = addressParts.join('');
    
    this.setData({
      'formData.native_place': fullAddress,
      'formData.native_province': province.name,
      'formData.native_city': city.name || '',
      'formData.native_district': district.name || ''
    });

    console.log('籍贯选择完成:', {
      native_place: fullAddress,
      native_province: province.name,
      native_city: city.name,
      native_district: district.name
    });
  },

  // 获取当前省市区选择器的范围
  getRegionRange() {
    const { regionData, regionIndex } = this.data;
    
    // 获取所有省份
    const provinces = regionData.provinces;
    const provinceNames = provinces.map(p => p.name);
    
    // 获取当前选中省份的城市
    const currentProvince = provinces[regionIndex[0]] || {};
    const cities = regionData.cities[currentProvince.code] || [];
    const cityNames = cities.map(c => c.name);
    
    // 获取当前选中城市的区县
    const currentCity = cities[regionIndex[1]] || {};
    const districts = regionData.districts[currentCity.code] || [];
    const districtNames = districts.map(d => d.name);
    
    // 返回三级选择器的数据
    return [provinceNames, cityNames, districtNames];
  }
});